package com.dream.cgomall.service.impl;


import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.dream.cgomall.service.ServiceResult;
import com.dream.cgomall.service.SmsService;
import com.dream.cgomallcore.util.NumRandom;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    private static final String BEFORE_KEY = "SMS::CODE:";
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 短信发送  Redis存储
     *
     * @param telephone 用户手机
     * @return 返回ServiceResult<String> success->true成功 / false失败 message错误信息
     */
    @Override
    public ServiceResult<String> sendSms(String telephone) {

        String code = NumRandom.getRandomNum(6);

        HashMap<String, Object> result = null;
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        restAPI.init("app.cloopen.com", "8883");
        // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883.
        restAPI.setAccount("8a216da87a332d53017a707abb6a1a91", "7814d5b623cb405489d37d3bc1c1de51");
        // 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在控制首页中看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN。
        restAPI.setAppId("8a216da87a332d53017a707abc631a97");
        // 请使用管理控制台中已创建应用的APPID。
        try {
            result = restAPI.sendTemplateSMS(telephone, "1", new String[]{code, "5"});
            System.out.println("SDKTestGetSubAccounts result=" + result);
            if (result.get("statusCode").equals("172003")) {
                System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
                return ServiceResult.badResult("短信发送失败");
            }
            redisTemplate.opsForValue().set(BEFORE_KEY + telephone, code, 5, TimeUnit.MINUTES);
            return ServiceResult.of(code);
        } catch (RuntimeException e) {
            return ServiceResult.badResult("手机号码有误，短信发送失败");
        }
    }

    /**
     * Redis验证
     *
     * @param telephone 用户手机
     * @return 验证码
     */
    @Override
    public ServiceResult<String> getSmsCode(String telephone, String code) {
        String Realcode = (String) redisTemplate.opsForValue().get(BEFORE_KEY + telephone);
        try {
            if (code == null || code == "") {
                return ServiceResult.notFound();
            }else if(Realcode == code || Realcode.equals(code)) {
                return ServiceResult.success();
            }
        } catch (RuntimeException e) {
            return ServiceResult.notFound();
        }
        return  ServiceResult.notFound();
    }

    /**
     * 在验证结束后进行清除
     *
     * @param telephone
     */
    @Override
    public Boolean remove(String telephone) {
        return redisTemplate.delete(BEFORE_KEY + telephone);

    }

    // @Autowired
    // RedisTemplate redisTemplate;
    // public static Client createClient() throws Exception {
    //     Config config = new Config()
    //             // 您的AccessKey ID
    //             .setAccessKeyId("LTAI5tGKiWHjQbJGhpsaPCYH")
    //             // 您的AccessKey Secret
    //             .setAccessKeySecret("N4MdLn2rDwUSiFXA5029oD27c2szQ4");
    //     // 访问的域名
    //     config.endpoint = "dysmsapi.aliyuncs.com";
    //     return new Client(config);
    // }
    // @Override
    // public ServiceResult<String> sendSms(String telephone)  {
    //     String code = NumRandom.getRandomNum(6);
    //     try {
    //         Client client = createClient();
    //         SendSmsRequest sendSmsRequest = new SendSmsRequest()
    //                 .setPhoneNumbers("15011287862")
    //
    //
    //                 .setTemplateParam(code);
    //         // 复制代码运行请自行打印 API 的返回值
    //         redisTemplate.opsForValue().set(telephone, code);
    //         client.sendSms(sendSmsRequest);
    //     }catch (Exception e){
    //         return ServiceResult.notFound();
    //     }
    //     return ServiceResult.of(code);
    // }
    //
    // @Override
    // public String getSmsCode(String telephone) {
    //     return (String) redisTemplate.opsForValue().get(telephone);
    // }
    //
    // @Override
    // public Boolean remove(String telephone) {
    //     return redisTemplate.delete(telephone);
    // }
}
